import {createRouter, createWebHashHistory, RouteRecordRaw} from 'vue-router'
import * as MenuUtil from '@/util/menu'
import useFastnavStore from '@/store/fastnav'
import useAuthStore from '@/store/auth'

const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login/index.vue'),
    },
    {
        path: '/',
        name: 'Main',
        component: () => import('@/views/Main/index.vue'),
        // redirect: '/Home',

        // children: [
        //     {
        //         path: '/Home',
        //         name: 'Home',
        //         component: () => import('@/views/Home/index.vue'),
        //     },
        //
        //     {
        //         path: '/sys/AdmUserPassword',
        //         name: 'AdmUserPassword',
        //         component: () => import('@/views/sys/AdmUserPassword.vue'),
        //     },
        //     {
        //         path: '/sys/AdmUser',
        //         name: 'AdmUser',
        //         component: () => import('@/views/sys/AdmUser.vue'),
        //     },
        //     {
        //         path: '/sys/config',
        //         name: 'config',
        //         children: [
        //             {
        //                 path: '/sys/config/index',
        //                 name: 'configInfo',
        //                 component: () => import('@/views/sys/config/index.vue'),
        //             },
        //         ]
        //     },
        //     {
        //         path: '/log/AdmUserLogin',
        //         name: 'AdmUserLogin',
        //         component: () => import('@/views/log/AdmUserLogin.vue'),
        //     },
        // ],
    },
    {
        path: '/:catchAll(.*)',
        component: () => import('@/views/Errors/404.vue'),
    },
]

const router = createRouter({
    routes,
    history: createWebHashHistory()
})


// 添加路由前置守卫，在这里判断Main是否有子路由，没有就添加。
let isAddRoute = false
router.beforeEach((to, _from, next) => {
    console.log(to);
    console.log(_from);
    //
    const authStore = useAuthStore()
    if (to.path == '/login' && authStore.isLogin) {
        next({path: '/'})
        return
    } else if (to.path != '/login' && !authStore.isLogin) {
        next({path: '/login'})
        return
    }

    if (!authStore.isLogin) {
        next()
        return
    }

    if (isAddRoute) {

        // 保存页签数据
        if (to.meta.desc) {
            const fastnavStore = useFastnavStore()
            fastnavStore.addData(to.meta.desc as string, to.path)
        }
        console.log(`to.path:${to.path}`)
        next()
        return
    }


    // 添加主页子路由
    isAddRoute = true

    const mainRoute = router.options.routes.find((v) => v.path == '/')!

    const [_genMenus, genRoutes] = MenuUtil.gen(1)

    mainRoute.redirect = genRoutes[0].path
    mainRoute.children = genRoutes

    router.addRoute(mainRoute)

    next({...to, replace: true})
})

export default router
